// 组织管理仓库
import { deepCopy, isEmptyObj } from '@/utils/tools';
import DepartmentDetailed from '@/components/ivew_conf/organization/department_detailed'
import CompanyDetailed from '@/components/ivew_conf/organization/company_detailed'
import { department } from '@/components/ivew_conf/organization/form_mod_conf';
import { submitAuditing, backOr } from '@/components/organization_tools/index'
import { totalBtns, companyBtns, departmentBnts } from '@/components/ivew_conf/organization/department_btns_conf'
import powerFilter from '@/components/ivew_conf/power/power_filter'

 
// 获取表单初始数据(新建表单)
function getInitFormData (key:string):any{
    
    let map = {
        companys: new CompanyDetailed (),
        departments: new DepartmentDetailed(),
        personal: {}
    };

    return map;
    
}

interface stateInf {

    companys: any[]
    currentData: organizationInf.departmentTreeItem
    personalList: any[]
    personalReqParams: {
        company:string,
        department:string
    }
    currentLoadFormData: any
    currentLoadForm: formInf.mod[]
    currentLoadFormBtns: commonInf.funBlockConf[]
    currentLoadFormMods: any[]
    currentAction: "create" | 'edit'
    currentType: "company" | 'department' | 'personal'
    
    foldingLayer: 'open' | 'close'

    organizationSelectDisabled:boolean 

}

class organization {

    namespaced: true

    state:stateInf = {

        // 组织列表
        companys: [],

        // 当前选中项数据
        currentData: {},

        // 当前选中项组织名称
        personalReqParams:{
            company: '',
            department: '',
        },

        // 人员列表
        personalList: [],

        // 动态表单所需数据
        currentLoadFormData: {},
        
        // 当前加载表单
        currentLoadForm: [],

        // 当前加载表单按键
        currentLoadFormBtns: [backOr,submitAuditing],

        // 当前加载表单组件
        currentLoadFormMods: [],

        // 表单操作状态
        currentAction: 'create',
        
        // 表单操作类型
        currentType: 'company',

        // 是否开启折叠层
        foldingLayer: 'close',
        
        // 组织管理, 选择组件是否禁用 按键操作
        organizationSelectDisabled: false
    }   
    
    mutations = {

        // 更新当前加载表单数据
        updataCurrentLoadFormData (state, data){
            state['currentLoadFormData'] = data;
        },
        
        // 更新当前公司列表
        updateCompanys(state, data){

            let powerConf = this['state']['mainStore']['powerConf'];
            
            state['companys'] = data
            
            
            this.dispatch('organizationStore/setinitPosition').then(currentData =>{

                let conf = {
                    complete: data,
                    ...currentData
                }
                
                // 权限过滤
                state['companys'] = powerFilter(conf, powerConf, 'organization')

            })
            
            
        },

        // 更新当前公司 部门名称（请求人员列表）
        updateCurrentNames(state, data){
            state['currentNames'] = data;
        },
        
        // 更新人员列表
        updatePersonalList (state, data){
            state['personalList'] = data || [];
        },
        
        // 更新人员列表请求参数
        updateReqPersonalList (state, data){
            state['personalReqParams'] = data;
        },


         // 切换折叠层
         foldingLayerSwitch(state:stateInf, data?:tableInf.flodKey){
            let newStatus:tableInf.flodKey = state.foldingLayer === 'open' ? 'close' : 'open';
            state.foldingLayer = data || newStatus;
            
        },
        
        // 按键配置开关
        organizationSelectDisabledSwitch (state,status?:boolean){
            state['organizationSelectDisabled'] = status !== undefined ? status : !state['organizationSelectDisabled']
        }
        
    }


    getters = {
        
        // 折叠层状态
        foldingLayerState (state:stateInf):boolean{
            return state.foldingLayer === 'open';
        },

        // 部门数据格式化配置
        departmentFomatConf (state){

            // 默认按键配置
            let dft = {
                totalBtns,
                companyBtns,
                departmentBnts
            };

            // 空值
            let empty = {
                totalBtns: [],
                companyBtns: [],
                departmentBnts: []
            }

            // 判断是否可操作
            let btns = state.organizationSelectDisabled ?  dft : empty 
            
            // 拼装数据结构
            function build({company, department}){

                const _company = {
                    children: company['sectors'] || [],
                    expand: false,
                    icon: 'icon-company',
                    company: company.name,
                    department: '',
                    btns: btns.companyBtns
                };

                let _department = {};

                if(department){
                    
                    _department = {

                        expand: false,
                        type: 'small',
                        icon: 'icon-loudong',
                        company: company.name,
                        department: department.name,
                        btns: btns.departmentBnts
    
                    }

                }
                
                return { 
                    _company,
                    _department
                }
            }

            const total = {

                name: '总公司',
                id: '',
                expand: true,
                icon: 'icon-crown',
                children: [],
                type: 'larg',
                btns: btns.totalBtns
                
            }

            return { build, total }

        }
        
    }

    actions = {

        // 设置初始数据位置
        setinitPosition ({state, commit, dispatch}){

            let userInfo = this.state['mainStore']['userBase'];
            let userCompany = userInfo['company'];
            let userDepartment = userInfo['department'];
            let companys = state['companys'][0]['children'];

            let currentCompanyCache = {};
            let currentDepartmentCache = {}

            // 请求人员数据
            dispatch('updataPersonalList', {
                company: userCompany,
                department: userDepartment
            })
            
            companys.forEach(company =>{

                let currentCompany = company['company'];
                let departments = company['children'];                

                // 展开列表项
                company['expand'] = true;
                
                if(currentCompany === userCompany){

                    // 缓存所属公司
                    currentCompanyCache = company

                    departments.forEach(department =>{
                        
                        if(department['department'] === userDepartment){

                            // 缓存所属部门
                            department['selected'] = true
                            currentDepartmentCache = department;
                            
                           
                            return 
                        }
                        
                    })
                }

                
            })

            return {
                company: currentCompanyCache,
                department: currentDepartmentCache
            }

        },

        // 设置当前选中项操作数据
        departmentEventIssue({state, commit, dispatch}, {data, action, type}){

            // 数据为空时 跳出（针对人员可取消选中项）
            if(isEmptyObj(data)){
                commit('foldingLayerSwitch', 'close')
                return false
            }

            let {department, personal} =  this.state['modConf']['organizationFormMods'];
            let companyMods = this.state['modConf']['companyForm'];
            let departmentMods = this.state['modConf']['departmentForm'];
            let personalForm = this.state['modConf']['personalForm'];
            let personalFormMod = this.state['modConf']['personalFormMod'];

            // 表单组件
            let typeMap = {

                company: department,
                department: department,
                personal: personal

            }
            
            // 组件配置
            let modsMap = {
                company: {
                    edit: companyMods.editForm,
                    create: companyMods.newForm
                },
                department: {
                    edit: departmentMods.editForm,
                    create: departmentMods.newForm
                },
                personal: {
                    edit: personalForm.newForm,
                    create: personalForm.newForm
                }
            }
            
            // 表单数据请求
            let dataMap = {

                edit: {
                    company: () =>{
                        dispatch('reqDepartment')
                    },
                    department: () =>{
                        dispatch('reqDepartment')
                    },
                    personal: () => {
                        dispatch('reqPersonal')
                     }
                },
                
                create: {
                    
                    company: () => {
                        state.currentLoadFormData = new CompanyDetailed ({
                            companyId: '',
                            parentSectorId: "ROOT",
                            kind: '分公司'
                        });
                    },
                    department: () => {
                        state.currentLoadFormData = new DepartmentDetailed ({
                            kind: '营业部',
                            businessModel: '直营',
                            companyId: data.id,
                            parentSectorId: data.id,
                        });
                    },
                    personal: () => {
                        state.currentLoadFormData = new personalFormMod({
                            company: data['company'],
                            department: data['department']
                        })
                    }

                }
                
            }

            // 更新数据
            state.currentData = data;
            state.currentAction = action;
            state.currentType = type;
            state.currentLoadFormMods = modsMap[type][action];
            state.currentLoadForm =  [typeMap[type]];
            
            dataMap[action][type]();

            commit('foldingLayerSwitch', 'open')
            
        },


        // 请求人员明细
        reqPersonal({state, commit, dispatch}){

            let data = state.currentData;

            return dispatch('request', {
                url: 'get/users/id',
                data: {
                    userId: data.id
                }
            }, {root:true})
                
        },
        
        // 请求部门明细
        reqDepartment ({state, commit, dispatch}){

            let data = state.currentData;

            return dispatch('request', {
                url: 'get/departments/id',
                data: {
                    id: data.id
                }
            }, {root:true})

        },

        // 请求人员列表数据
        updataPersonalList({state, commit, dispatch}, data){

            let {company, department} = data;
            
            // 更新人员查询参数
            commit('updateReqPersonalList', {
                company,
                department
            })

           return dispatch('request', {
                url: 'get/users',
                data: {}
            },{root:true})

        },
        
        // 刷新组织列表
        initOrganization({state, commit, dispatch}, data){

            return dispatch('request', {
                url: 'get/companys',
                data: {
                    all:1
                }
            }, {root:true})
            
        }

    }
}

export default organization